package bootstrap

import (
	models "devops-dcc/internal/model"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func InitDatabase() error {
	var err error
	db, err = gorm.Open(mysql.Open(cfg.Database.DSN), &gorm.Config{
		//Logger: logger.Logger,
	})
	if err != nil {
		return err
	}

	sqlDB, err := db.DB()
	if err != nil {
		return err
	}

	sqlDB.SetMaxIdleConns(cfg.Database.MaxIdleConns)
	sqlDB.SetMaxOpenConns(cfg.Database.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(cfg.Database.ConnMaxLifetime)

	// 执行迁移
	if err := performMigrations(); err != nil {
		return err
	}

	return nil
}

// 数据库模型迁移
func performMigrations() error {
	return db.AutoMigrate(
		&models.Platform{},
		&models.Environment{},
		&models.PlatformEnvironment{},
	)
}
